//
//  XMPicwordDetailView.m
//  XMJJ_zml
//
//  Created by 丁浩 on 2025/7/2.
//

#import "XMPicwordDetailView.h"
#import "SDCycleScrollView.h"
#import "XMPicwordCommentModel.h"

#import "XMPicwordCommentHeadView.h"
#import "XMPicwordCommentCell.h"
#import "XMPicwordCommentView.h"

@interface XMPicwordDetailView () <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UIImageView *avatarImgView;
@property (nonatomic, strong) UILabel *nameLabel;
@property (nonatomic, strong) UIButton *attentionBtn;

@property (nonatomic, strong) UITableView *tbl;

@property (nonatomic, strong) SDCycleScrollView *imgScrollView;
@property (nonatomic, strong) UILabel *contentLabel;
@property (nonatomic, strong) UILabel *dateLabel;

@property (nonatomic, strong) UIView *lineView;

@property (nonatomic, strong) UIButton *commentNumBtn;
@property (nonatomic, strong) UIButton *likeBtn;

@property (nonatomic, strong) NSMutableArray *commentModelArr;

@property (nonatomic, copy) NSString *userId;
@property (nonatomic, copy) NSString *commentId;
@property (nonatomic, copy) NSString *commentLevel;
@property (nonatomic, copy) NSString *totalNumStr;
@property (nonatomic, assign) BOOL attentionStatus;

@end

@implementation XMPicwordDetailView

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self creatUI];
    }
    return self;
}

- (void)creatUI {
    [self addSubview:self.navView];
    self.navView.backgroundColor = kColorHEX(0xF7F7F7);
    [self.navView addSubview:self.avatarImgView];
    [self.navView addSubview:self.nameLabel];
    UIButton *attentionBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(13.0) frame:CGRectMake(self.navView.width - KScaleWidth(44.0) - KScaleWidth(50.0), self.navView.height - 44.0 + (44 - KScaleWidth(25.0))/2, KScaleWidth(50.0), KScaleWidth(25.0)) title:@"关注" titleColor:kColorHEX(0x333333)];
    [attentionBtn setTitle:@"已关注" forState:UIControlStateSelected];
    [attentionBtn setBackgroundImage:[UIImage imageWithColor:kColorHEX(0xFFD800)] forState:UIControlStateNormal];
    [attentionBtn setBackgroundImage:[UIImage imageWithColor:kColorHEX(0xFFD800)] forState:UIControlStateSelected];
    [attentionBtn setCornerRadius:attentionBtn.height/2];
    [attentionBtn addTarget:self action:@selector(attention:) forControlEvents:UIControlEventTouchUpInside];
    [self.navView addSubview:attentionBtn];
    _attentionBtn = attentionBtn;
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, KScaleWidth(400.0))];
    headView.backgroundColor = kColorHEX(0xffffff);
    [headView addSubview:self.imgScrollView];
    [headView addSubview:self.contentLabel];
    [headView addSubview:self.dateLabel];
    [headView addSubview:self.lineView];
    
    [self addSubview:self.tbl];
    _tbl.tableHeaderView = headView;
    
    UIButton *commentBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(15.0) frame:CGRectMake(KScaleWidth(10.0), self.height - kBottomLayout - KScaleWidth(78.0) + KScaleWidth(16.0), self.width - KScaleWidth(10.0) - KScaleWidth(156.0), KScaleWidth(42.0)) title:@"评论一下" titleColor:kColorHEX(0x9E9E9E)];
    commentBtn.backgroundColor = kColorHEX(0xF6F6F6);
    [commentBtn setCornerRadius:commentBtn.height/2];
    [commentBtn addTarget:self action:@selector(commentAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:commentBtn];
    
    UIButton *commentNumBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(15.0) frame:CGRectMake(self.width - KScaleWidth(156.0), commentBtn.y, KScaleWidth(156.0)/2, commentBtn.height) title:@"0" titleColor:kColorHEX(0x333333) image:@"find_comment_icon"];
    [commentNumBtn layoutButtonWithEdgeInsetsStyle:CSButtonEdgeInsetsStyleLeft ImageTitleSpace:KScaleWidth(2.0)];
    [self addSubview:commentNumBtn];
    
    _likeBtn = [UIButton buttonWithType:UIButtonTypeCustom font:KFontSize(15.0) frame:CGRectMake(self.width - KScaleWidth(156.0)/2, commentBtn.y, KScaleWidth(70.0), commentBtn.height) title:@"0" titleColor:kColorHEX(0x333333) image:@"find_comment_like_icon"];
    [_likeBtn setImage:ImageNamed(@"find_comment_like_icon_select") forState:UIControlStateSelected];
    [_likeBtn addTarget:self action:@selector(likeAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:_likeBtn];
    _commentId = @"";
    _commentLevel = @"0";
    _totalNumStr = @"0";
}

- (void)setContentWithDetailModel:(XMPicwordDetailModel *)detailModel {
    [_avatarImgView sd_setImageWithURL:[NSURL URLWithString:detailModel.avatar]];
    _nameLabel.text = detailModel.nickname;
    _userId = detailModel.userId;
    _attentionStatus = detailModel.isAttention;
    _imgScrollView.imageURLStringsGroup = [detailModel.images componentsSeparatedByString:@","];
    CGFloat height = [detailModel.content getHeightWithFont:KScaleWidth(14.0) withWidth:_contentLabel.width] + KScaleWidth(10.0);
    _contentLabel.height = MAX(height, KScaleWidth(20.0));
    _contentLabel.text = detailModel.content;
    _dateLabel.y = _contentLabel.maxY + KScaleWidth(5.0);
    NSString *dateStr = [[NSDate dateWithTimeIntervalSince1970:[detailModel.createTime integerValue]/1000] dateStringWithFormat:@"yyyy-MM-dd HH:mm"];
    _dateLabel.text = [NSString stringWithFormat:@"发布于：%@", dateStr];
    _lineView.y = _dateLabel.maxY + KScaleWidth(20.0);
    _dateLabel.superview.height = _lineView.maxY;

    _attentionBtn.selected = detailModel.isAttention;
    _likeBtn.selected = detailModel.isLike;
    [_likeBtn setTitle:detailModel.likeCount forState:UIControlStateNormal];
    [_likeBtn setTitle:detailModel.likeCount forState:UIControlStateSelected];
    [_commentNumBtn setTitle:detailModel.commentCount forState:UIControlStateNormal];
    [_likeBtn layoutButtonWithEdgeInsetsStyle:CSButtonEdgeInsetsStyleLeft ImageTitleSpace:KScaleWidth(5.0)];
    [_commentNumBtn layoutButtonWithEdgeInsetsStyle:CSButtonEdgeInsetsStyleLeft ImageTitleSpace:KScaleWidth(5.0)];
}

- (void)setContentWithCommentModelArr:(NSArray *)commentModelArr
                             totalNum:(NSString *)totalNumStr
                                 page:(NSInteger)page {
    [_tbl.mj_header endRefreshing];
    if (page == 1) {
        [self.commentModelArr removeAllObjects];
    }
    if (commentModelArr.count < 10) {
        [_tbl.mj_footer endRefreshingWithNoMoreData];
    }
    else {
        [_tbl.mj_footer endRefreshing];
    }
    _totalNumStr = totalNumStr;
    [self.commentModelArr addObjectsFromArray:commentModelArr];
}

- (void)loadSuccess {
    [_tbl reloadData];
}

//点赞
- (void)likeAction:(UIButton *)button {
    if (self.delegate && [self.delegate respondsToSelector:@selector(picwordLikeAction)]) {
        [self.delegate picwordLikeAction];
    }
}

//关注
- (void)attention:(UIButton *)button {
    if (self.delegate && [self.delegate respondsToSelector:@selector(picwordAttentionWithUserId:isAttention:)]) {
        [self.delegate picwordAttentionWithUserId:_userId
                                      isAttention:_attentionStatus];
    }
}

//评论
- (void)commentAction:(UIButton *)button {
    XMPicwordCommentView *commentView = [[XMPicwordCommentView alloc] initWithFrame:self.bounds];
    [commentView setContentWithName:@"说点什么吧！"];
    [self addSubview:commentView];
    [commentView show];
    XMWeakSelf;
    commentView.publishBlock = ^(NSString * _Nonnull contentStr) {
        if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(commentPublishWithContent:commentId:commentLevel:)]) {
            [weakSelf.delegate commentPublishWithContent:contentStr
                                               commentId:weakSelf.commentId
                                            commentLevel:weakSelf.commentLevel];
        }
    };
}

#pragma mark - BtnActionSuccess
//关注成功
- (void)attentionSuccess:(BOOL)isAttention {
    _attentionStatus = isAttention;
    _attentionBtn.selected = isAttention;
}

//点赞成功
- (void)picwordLikeSuccess {
    _likeBtn.selected = !_likeBtn.selected;
}

#pragma mark - Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.commentModelArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    XMPicwordCommentModel *commentModel = _commentModelArr[section];
    return commentModel.replys.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    XMPicwordCommentModel *commentModel = self.commentModelArr[section];
    CGFloat height = [commentModel.content getHeightWithFont:KScaleWidth(14.0) withWidth:self.width - KScaleWidth(10.0) - KScaleWidth(38.0) - KScaleWidth(6.0) - KScaleWidth(10.0)] + KScaleWidth(5.0);
    
    return MAX(height, KScaleWidth(20.0)) + KScaleWidth(30.0) + KScaleWidth(42.0);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    XMPicwordCommentModel *commentModel = self.commentModelArr[section];
    XMPicwordCommentHeadView *headView = [[XMPicwordCommentHeadView alloc] initWithFrame:CGRectMake(0, 0, self.width, KScaleWidth(10.0))];
    [headView setContentWithCommentModel:commentModel];
    XMWeakSelf;
    headView.likeBlock = ^{
        if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(commentLikeWithCommentId:)]) {
            [weakSelf.delegate commentLikeWithCommentId:commentModel.objectId];
        }
    };
    headView.commentBlock = ^{
        XMPicwordCommentView *commentView = [[XMPicwordCommentView alloc] initWithFrame:self.bounds];
        [commentView setContentWithName:commentModel.userNickName];
        [self addSubview:commentView];
        [commentView show];
        XMWeakSelf;
        commentView.publishBlock = ^(NSString * _Nonnull contentStr) {
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(commentPublishWithContent:commentId:commentLevel:)]) {
                [weakSelf.delegate commentPublishWithContent:contentStr
                                                   commentId:commentModel.objectId
                                                commentLevel:@"1"];
            }
        };
    };
    return headView;
//    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, KScaleWidth(44.0))];
//    headView.backgroundColor = kColorHEX(0xffffff);
//    UILabel *totalLabel = [[UILabel alloc] initWithFrame:CGRectMake(KScaleWidth(10.0), 0, headView.width - KScaleWidth(10.0), headView.height) font:KBoldFontSize(16.0) textColor:kColorHEX(0x333333)];
//    totalLabel.text = [NSString stringWithFormat:@"全部评价（%@）", _totalNumStr];
//    [headView addSubview:totalLabel];
//    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    XMPicwordCommentModel *commentModel = self.commentModelArr[indexPath.row];
    CGFloat width = kScreenWidth - KScaleWidth(38.0) - KScaleWidth(10.0) - KScaleWidth(6.0) - KScaleWidth(10.0) - KScaleWidth(10.0) - KScaleWidth(28.0) - KScaleWidth(6.0) - KScaleWidth(10.0);
    CGFloat height = [commentModel.content getHeightWithFont:KScaleWidth(14.0) withWidth:width] + KScaleWidth(5.0);
    
    return MAX(height, KScaleWidth(20.0)) + KScaleWidth(35.0) + KScaleWidth(42.0);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XMPicwordCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:@"XMPicwordCommentCellName" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    XMPicwordCommentModel *commentModel = _commentModelArr[indexPath.section];
    XMPicwordCommentModel *subModel = commentModel.replys[indexPath.row];
    [cell setContentWithCommentModel:subModel];
    XMWeakSelf;
    cell.likeBlock = ^{
        if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(commentLikeWithCommentId:)]) {
            [weakSelf.delegate commentLikeWithCommentId:subModel.objectId];
        }
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    XMPicwordCommentModel *commentModel = _commentModelArr[indexPath.row];
    XMPicwordCommentView *commentView = [[XMPicwordCommentView alloc] initWithFrame:self.bounds];
    [commentView setContentWithName:commentModel.userNickName];
    [self addSubview:commentView];
    [commentView show];
    XMWeakSelf;
    commentView.publishBlock = ^(NSString * _Nonnull contentStr) {
        if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(commentPublishWithContent:commentId:commentLevel:)]) {
            [weakSelf.delegate commentPublishWithContent:contentStr
                                               commentId:commentModel.objectId
                                            commentLevel:@"2"];
        }
    };
}

#pragma mark - Init
- (SDCycleScrollView *)imgScrollView {
    if (!_imgScrollView) {
        _imgScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(KScaleWidth(10.0), KScaleWidth(10.0), self.width - KScaleWidth(10.0)*2, KScaleWidth(243.0)) imageNamesGroup:@[]];
        [_imgScrollView setCornerRadius:KScaleWidth(16.0)];
        _imgScrollView.autoScrollTimeInterval = 2;
    }
    return _imgScrollView;
}

- (UIImageView *)avatarImgView {
    if (!_avatarImgView) {
        _avatarImgView = [[UIImageView alloc] initWithFrame:CGRectMake(44, kNavagationBarH - 44, 44, 44)];
        [_avatarImgView setCornerRadius:_avatarImgView.height/2];
    }
    return _avatarImgView;
}

- (UILabel *)nameLabel {
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.avatarImgView.maxX + KScaleWidth(8.0), _avatarImgView.y, self.navView.width - _avatarImgView.maxX - KScaleWidth(8.0) - KScaleWidth(44.0) - KScaleWidth(50.0) - KScaleWidth(10.0), _avatarImgView.height) font:KFontSize(18.0) textColor:kColorHEX(0x333333)];
    }
    return _nameLabel;
}

- (UILabel *)contentLabel {
    if (!_contentLabel) {
        _contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(KScaleWidth(10.0), self.imgScrollView.maxY + KScaleWidth(5.0), self.width - KScaleWidth(10.0)*2, KScaleWidth(20.0)) font:KFontSize(14.0) textColor:kColorHEX(0x666666)];
        _contentLabel.numberOfLines = 0;
    }
    return _contentLabel;
}

- (UILabel *)dateLabel {
    if (!_dateLabel) {
        _dateLabel = [[UILabel alloc] initWithFrame:CGRectMake(KScaleWidth(10.0), self.contentLabel.maxY, self.width - KScaleWidth(10.0)*2, KScaleWidth(20.0)) font:KFontSize(14.0) textColor:kColorHEX(0x999999) textAlignment:NSTextAlignmentRight];
    }
    return _dateLabel;
}

- (UIView *)lineView {
    if (!_lineView) {
        _lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.width, KScaleWidth(10.0))];
        _lineView.backgroundColor = kColorHEX(0xF7F7F7);
    }
    return _lineView;
}

- (UITableView *)tbl {
    if (!_tbl) {
        _tbl = [[UITableView alloc] initWithFrame:CGRectMake(0, kNavagationBarH, self.width, self.height - kNavagationBarH - KScaleWidth(78.0) - kBottomLayout) style:UITableViewStyleGrouped];
        _tbl.delegate = self;
        _tbl.dataSource = self;
        _tbl.backgroundColor = kColorHEX(0xF7F7F7);
        _tbl.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tbl registerClass:[XMPicwordCommentCell class] forCellReuseIdentifier:@"XMPicwordCommentCellName"];
        if (@available(iOS 15.0, *)) {
            _tbl.sectionHeaderTopPadding = 0;
        } else {
            _tbl.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            // Fallback on earlier versions
        }
    }
    return _tbl;
}

- (NSMutableArray *)commentModelArr {
    if (!_commentModelArr) {
        _commentModelArr = [NSMutableArray array];
    }
    return _commentModelArr;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
